//
//  KLApplyForKeyViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/9/25.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLApplyForKeyViewController.h"
#import "KLHelp.h"
#import "HemaConst.h"
#import "JRToast.h"
#import "KLHttpAPI.h"
#import "Masonry.h"
#import "IdentifierValidator.h"
#import "BeeCloud+Utils.h"
#import "KLRechargeViewController.h"
#import "UIAlertView+Blocks.h"
#import "UUDatePicker.h"
#import "KLHistoryApplyKeyListTableViewController.h"

@interface KLApplyForKeyViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,BeeCloudDelegate,UIAlertViewDelegate,UIActionSheetDelegate>
{
    UIView *fatherView1;
    UIView *fatherView2;
    UIButton *editMultiselectBtn; //编辑多选按钮
    UIButton *timeBtnStart; //推出开始时间选择器
    UIButton *timeBtnEnd; //推出结束时间选择器
    UITextView *messageView; //留言面板
    UILabel *placeHoldeLabel; //UITextView的占位符
    
    UIView *timeCoverView; //时间选择器的蒙板
    
    NSString *minTotalFee; //给锁主的最低金额
    NSString *factPayFee; //实际支付给锁主的金额
    NSString *msg; //给锁主的留言
    NSIndexPath *selectIndexPath; //当前选中行
    NSString *typeSelect;//选择申请的type类型
}
@property(nonatomic,strong) UITextField *phoneTF; //输入锁主手机号
@property(nonatomic,strong) UIImageView *noticeImage; //提示手机号输入是否正确
@property(nonatomic,strong) UITableView *lockListView; //可被暴露给申请人的锁列表

@property(nonatomic,strong) NSMutableArray *getAllLockList; //所有拿到的锁列表
@property(nonatomic,strong) NSMutableArray *selectedLockListArr; //被选中的锁列表

@property (nonatomic,strong) NSString *money; //在线支付的钱数
@property (nonatomic,strong) NSString *trade_no; //支付订单号

@property (nonatomic,strong) NSString *startYear;
@property (nonatomic,strong) NSString *startMonth;
@property (nonatomic,strong) NSString *startDay;
@property (nonatomic,strong) NSString *startHour;
@property (nonatomic,strong) NSString *startMin;

@property (nonatomic,strong) NSString *endYear;
@property (nonatomic,strong) NSString *endMonth;
@property (nonatomic,strong) NSString *endDay;
@property (nonatomic,strong) NSString *endHour;
@property (nonatomic,strong) NSString *endMin;
@end

@implementation KLApplyForKeyViewController

-(NSMutableArray *)selectedLockListArr{
    if(!_selectedLockListArr){
        _selectedLockListArr = [NSMutableArray array];
    }
    return _selectedLockListArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"申请钥匙";
    //初始化导航栏
    self.navigationController.navigationBarHidden = NO;
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
    UIButton * applyListBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30.0f, 30.0f)];
    [applyListBtn setImage:[UIImage imageNamed:@"申请历史记录"] forState:UIControlStateNormal];
    [applyListBtn addTarget:self action:@selector(applyList:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *applyListBtnItem = [[UIBarButtonItem alloc] initWithCustomView:applyListBtn];
    [applyListBtnItem setStyle:UIBarButtonItemStyleBordered];
    [self.navigationItem setRightBarButtonItem:applyListBtnItem];
    
    //初始化主界面
    self.view.backgroundColor = [KLHelp mainBlueColor];
    //父视图1
    fatherView1 = [[UIView alloc]initWithFrame:CGRectMake(5, 5, UI_View_Width-10, 80)];
    fatherView1.backgroundColor = [UIColor whiteColor];
    fatherView1.layer.masksToBounds = YES;
    fatherView1.layer.cornerRadius = 8;
    [self.view addSubview:fatherView1];
    //label显示输入手机号
    UILabel *phoneLabel = [[UILabel alloc]init];
    phoneLabel.text = @"锁主手机号:";
    phoneLabel.font = [UIFont systemFontOfSize:16];
    [fatherView1 addSubview:phoneLabel];
    [phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(5);
        make.top.mas_equalTo(10);
    }];
    //输入手机号的UITextField
    self.phoneTF = [[UITextField alloc]init];
    self.phoneTF.placeholder = @"输入锁主手机号:";
    self.phoneTF.textColor = RGB_UI_COLOR(103, 78, 167);
    self.phoneTF.font = [UIFont systemFontOfSize:15];
    self.phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.phoneTF addTarget:self action:@selector(textfieldChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.phoneTF becomeFirstResponder];
    [fatherView1 addSubview:self.phoneTF];
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(UI_View_Width/5*3);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(35);
        make.left.mas_equalTo(40);
    }];
    //UITextField的下划线
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 28, UI_View_Width/5*3, 0.5)];
    line.backgroundColor = [UIColor blackColor];
    line.alpha = 0.5;
    [self.phoneTF addSubview:line];
    //提示输入手机号是否正确的图片
    self.noticeImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"警告星号"]];
    [fatherView1 addSubview:self.noticeImage];
    [self.noticeImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(12);
        make.height.mas_equalTo(12);
        make.right.equalTo(self.phoneTF).with.offset(25);
        make.bottom.equalTo(self.phoneTF).with.offset(-3);
    }];
    //父视图2
    fatherView2 = [[UIView alloc]initWithFrame:CGRectMake(5, 90, UI_View_Width-10, UI_View_Height-100)];
    fatherView2.backgroundColor = RGB_UI_COLOR(235, 235, 235);
    fatherView2.layer.masksToBounds = YES;
    fatherView2.layer.cornerRadius = 8;
    [self.view addSubview:fatherView2];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 监听输入手机号改变
-(void)textfieldChanged:(UITextField *)textField{
    if([IdentifierValidator isValid:IdentifierTypePhone value:textField.text]){
        if([textField.text isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]]){
            [KLHelp showTextHUDforView:self.view text:@"您无法向自己申请钥匙"];
            return;
        }
        self.noticeImage.image = [UIImage imageNamed:@"正确对勾"];
        [textField resignFirstResponder];
        [KLHelp showHUDAddedTo:self.view animated:YES];
        [KLHttpAPI requestAllowedToBeApplyLockListWIthMoblie:textField.text completionHandler:^(MKNetworkOperation *operation) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            NSLog(@"允许的锁列表返回:%@",operation.responseString);
            NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
            if(isSuccess.integerValue == 1){
                NSArray *tempArr = [NSArray arrayWithArray:[operation.responseJSON objectForKey:@"infor"]];
                if(![tempArr isKindOfClass:[NSNull class]] && tempArr.count != 0){
                    self.getAllLockList = [NSMutableArray array];
                    NSMutableArray *locks = [NSMutableArray array];
                    NSMutableArray *brunchs = [NSMutableArray array];
                    [tempArr enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        NSString *type = [(NSDictionary *)obj objectForKey:@"type"];
                        if(type.integerValue == 1 || type.integerValue == 2){
                            [brunchs addObject:(NSDictionary *)obj];
                        }else if(type.integerValue == 0 || type.integerValue == 4){
                            [locks addObject:(NSDictionary *)obj];
                        }
                    }];
                    if(brunchs.count != 0){
                        [self.getAllLockList addObject:brunchs];
                    }
                    if(locks.count != 0){
                        [self.getAllLockList addObject:locks];
                    }
                    [self showSecondLevelView];
                }else{
                    [KLHelp showTextHUDforView:self.view text:@"该用户没有可被申请的锁或钥匙串！"];
                }
            }else{
                [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
            }
        } errorHandler:^(NSString *error) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            [KLHelp showTextHUDforView:self.view text:@"网络连接中断"];
        }];
    }else{
        self.noticeImage.image = [UIImage imageNamed:@"警告星号"];
         [fatherView2.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
}

#pragma mark - 二级显示控件
-(void)showSecondLevelView{
    selectIndexPath = nil;
    //创建锁列表
    self.lockListView = [[UITableView alloc]initWithFrame:CGRectMake(10, 5, UI_View_Width-50, UI_View_Height/4) style:UITableViewStylePlain];
    self.lockListView.rowHeight = 40;
    self.lockListView.layer.masksToBounds = YES;
    self.lockListView.layer.cornerRadius = 10;
    self.lockListView.tableFooterView = [[UIView alloc]init];
    self.lockListView.delegate = self;
    self.lockListView.dataSource = self;
    [fatherView2 addSubview:self.lockListView];
    //起始时间选择按钮
    timeBtnStart = [[UIButton alloc]init];
    [fatherView2 addSubview:timeBtnStart];
    timeBtnStart.layer.masksToBounds = YES;
    timeBtnStart.layer.cornerRadius = 8;
    timeBtnStart.titleLabel.font = [UIFont systemFontOfSize:14];
    [timeBtnStart setBackgroundColor:RGB_UI_COLOR(153, 153, 255)];
    [timeBtnStart addTarget:self action:@selector(timeSelection:) forControlEvents:UIControlEventTouchUpInside];
    [timeBtnStart mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(fatherView2).with.offset(10);
        make.width.mas_equalTo(UI_View_Width/2-20);
        make.bottom.equalTo(self.lockListView).with.offset(45);
        make.height.mas_equalTo(35);
    }];
    [timeBtnStart setImage:[UIImage imageNamed:@"canadar"] forState:UIControlStateNormal];
    timeBtnStart.imageEdgeInsets = UIEdgeInsetsMake(5,5,5,UI_View_Width/2-20-25);//上左下右
    [timeBtnStart setTitle:@"起始时间" forState:UIControlStateNormal];
    timeBtnStart.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);//上左下右
    //结束时间选择按钮
    timeBtnEnd = [[UIButton alloc]init];
    [fatherView2 addSubview:timeBtnEnd];
    timeBtnEnd.layer.masksToBounds = YES;
    timeBtnEnd.layer.cornerRadius = 8;
    timeBtnEnd.titleLabel.font = [UIFont systemFontOfSize:14];
    [timeBtnEnd setBackgroundColor:RGB_UI_COLOR(153, 153, 255)];
    [timeBtnEnd addTarget:self action:@selector(timeSelection:) forControlEvents:UIControlEventTouchUpInside];
    [timeBtnEnd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(fatherView2).with.offset(-10);
        make.width.mas_equalTo(UI_View_Width/2-20);
        make.bottom.equalTo(self.lockListView).with.offset(45);
        make.height.mas_equalTo(35);
    }];
    [timeBtnEnd setImage:[UIImage imageNamed:@"canadar"] forState:UIControlStateNormal];
    timeBtnEnd.imageEdgeInsets = UIEdgeInsetsMake(5,5,5,UI_View_Width/2-20-25);//上左下右
    [timeBtnEnd setTitle:@"结束时间" forState:UIControlStateNormal];
    timeBtnEnd.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);//上左下右
    //留言面板
    messageView = [UITextView new];
    messageView.layer.masksToBounds = YES;
    messageView.layer.cornerRadius = 8;
    messageView.editable = YES;
    messageView.delegate = self;
    messageView.textColor = [UIColor purpleColor];
    messageView.font = [UIFont systemFontOfSize:16];
    messageView.scrollEnabled = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;//消除影响（iOS7 如果把UIscrollView 加在导航中一般内容会向下走64）
    [fatherView2 addSubview:messageView];
    [messageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(timeBtnStart).with.offset(45);
        make.left.mas_equalTo(10);
        make.width.mas_equalTo(UI_View_Width-30);
        make.height.mas_equalTo(UI_View_Height/5);
    }];
    //留言板的占位符
    placeHoldeLabel = [[UILabel alloc]init];
    placeHoldeLabel.text = @"给锁主的留言...";
    placeHoldeLabel.font = [UIFont systemFontOfSize:16];
    placeHoldeLabel.textColor = [UIColor lightGrayColor];
    [messageView addSubview:placeHoldeLabel];
    [placeHoldeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(5);
        make.top.mas_equalTo(5);
    }];
    //提交按钮
    UIButton *submitBtn = [[UIButton alloc]init];
    UIEdgeInsets insets = UIEdgeInsetsMake(15, 15, 15, 15);
    UIImage *image = [[UIImage imageNamed:@"button_normal"] resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    [submitBtn setBackgroundImage:image forState:UIControlStateNormal];
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [fatherView2 addSubview:submitBtn];
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(fatherView2);
        make.width.mas_equalTo(UI_View_Width/2);
        make.height.mas_equalTo(40);
        make.bottom.equalTo(messageView).with.offset(65);
    }];
    [submitBtn addTarget:self action:@selector(submitRequest:) forControlEvents:UIControlEventTouchUpInside];
}-(void)timeSelection:(UIButton *)sender{
    [self showTimeControlView:sender];
}-(void)submitRequest:(UIButton *)sender{
    [self.view endEditing:YES];
    if(self.startYear == nil || self.endYear == nil){
        [KLHelp showTextHUDforView:self.view text:@"请选择时间期限"];
        return;
    }
    if(self.selectedLockListArr.count == 0){
        [KLHelp showTextHUDforView:self.view text:@"请选择至少一把锁进行申请！"];
        return ;
    }else{
        msg = messageView.text;
        //去除掉首尾的空白字符和换行字符
        msg = [msg stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        msg = [msg stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        msg = [msg stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        
        NSString *startTime = [NSString stringWithFormat:@"%@-%@-%@ %@:%@:00",self.startYear,self.startMonth,self.startDay,self.startHour,self.startMin];
        NSString *endTime = [NSString stringWithFormat:@"%@-%@-%@ %@:%@:00",self.endYear,self.endMonth,self.endDay,self.endHour,self.endMin];
       
        [KLHelp showHUDAddedTo:self.view animated:YES];
        if(typeSelect.integerValue == 1 || typeSelect.integerValue == 2){
            [KLHttpAPI getKeyGroupTotalFeeWithStartDate:startTime endDate:endTime style:typeSelect authorize:@"0" group_id:[self.selectedLockListArr lastObject] power:@"00" completionHandler:^(MKNetworkOperation *operation) {
                [KLHelp hideAllHUDsForView:self.view animated:YES];
                NSLog(@"operation:%@",operation.responseString);
                NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    NSString *singleFee = [operation.responseJSON objectForKey:@"infor"];
                    minTotalFee = [NSString stringWithFormat:@"%.2f",singleFee.doubleValue*self.selectedLockListArr.count];
                    //弹出输入金额框
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"正在进行申请钥匙" message:[NSString stringWithFormat:@"最低输入金额:%@元",minTotalFee] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                    //设置输入框的键盘类型
                    UITextField *tf = [alert textFieldAtIndex:0];
                    tf.keyboardType = UIKeyboardTypeNumberPad;
                    tf.placeholder = @"请输入支付给锁主的金额(元),如:1";
                    [alert show];
                }else{
                    [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp hideAllHUDsForView:self.view animated:YES];
            }];
        }else if (typeSelect.integerValue == 0 || typeSelect.integerValue == 4){
            [KLHttpAPI requestGetChild_KeyPriceWithStartDate:startTime endDate:endTime completionHandler:^(MKNetworkOperation *operation) {
                [KLHelp hideAllHUDsForView:self.view animated:YES];
                NSLog(@"operation:%@",operation.responseString);
                NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    NSString *singleFee = [operation.responseJSON objectForKey:@"infor"];
                    minTotalFee = [NSString stringWithFormat:@"%.2f",singleFee.doubleValue*self.selectedLockListArr.count];
                    //弹出输入金额框
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"正在进行申请钥匙" message:[NSString stringWithFormat:@"最低输入金额:%@元",minTotalFee] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                    //设置输入框的键盘类型
                    UITextField *tf = [alert textFieldAtIndex:0];
                    tf.keyboardType = UIKeyboardTypeNumberPad;
                    tf.placeholder = @"请输入支付给锁主的金额(元),如:1";
                    [alert show];
                }else{
                    [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp hideAllHUDsForView:self.view animated:YES];
            }];
        }
    }
}

#pragma mark - UITextView的代理方法
//已经进入编辑模式
- (void)textViewDidBeginEditing:(UITextView *)textView{
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = CGRectMake(0, -145, UI_View_Width, UI_View_Height);
    }];
    placeHoldeLabel.text = nil;
}

//当文字改变时调用
-(void)textViewDidChange:(UITextView *)textView {
    if(textView.text.length > 140){
        [JRToast showWithText:@"不能输入超过140个字！"];
        [textView.text substringToIndex:140];
    }
}

//已经结束/退出编辑模式
- (void)textViewDidEndEditing:(UITextView *)textView{
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = CGRectMake(0, 64, UI_View_Width, UI_View_Height);
    }];
    if(textView.text.length == 0){
        placeHoldeLabel.text = @"给锁主的留言...";
    }
}

#pragma mark - UITableView相关方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.getAllLockList.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSMutableArray *sectionArr = self.getAllLockList[section];
    return sectionArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"lockCanApplyFor"];
    if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"lockCanApplyFor"];
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if(selectIndexPath != nil && indexPath.row == selectIndexPath.row){
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    
    NSDictionary *lockDic = self.getAllLockList[indexPath.section][indexPath.row];
    cell.textLabel.text = [lockDic objectForKey:@"name"];
    cell.textLabel.textColor = [UIColor grayColor];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSDictionary *lockDic = self.getAllLockList[indexPath.section][indexPath.row];
    NSLog(@"lockDic:%@",lockDic);
    
    if(self.selectedLockListArr.count == 0){
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [self.selectedLockListArr addObject:[lockDic objectForKey:@"id"]];
        typeSelect = [lockDic objectForKey:@"type"];
    }else{
        UITableViewCell *celled = [tableView cellForRowAtIndexPath:selectIndexPath];
        NSString *lockLastId = self.selectedLockListArr.lastObject;
        NSString *lockCurrentId = [lockDic objectForKey:@"id"];
        if((indexPath.section == selectIndexPath.section) && (indexPath.row == selectIndexPath.row)){
            [self.selectedLockListArr removeObject:lockCurrentId];
            celled.accessoryType = UITableViewCellAccessoryNone;
            typeSelect = nil;
        }else{
            [self.selectedLockListArr removeObject:lockLastId];
            [self.selectedLockListArr addObject:lockCurrentId];
            celled.accessoryType = UITableViewCellAccessoryNone;
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            typeSelect = [lockDic objectForKey:@"type"];
        }
    }
    NSLog(@"selectedLockListArr:%@",self.selectedLockListArr);
    selectIndexPath = indexPath;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSArray *arr = self.getAllLockList[section];
    NSDictionary *dic = arr[0];
    NSString *type = [dic objectForKey:@"type"];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 25)];
    label.backgroundColor = RGB_UI_COLOR(241, 241, 241);
    if(type.integerValue == 1 || type.integerValue == 2){
        label.text = @"  钥匙串";
    }else if (type.integerValue == 0 || type.integerValue == 4){
        label.text = @"  锁";
    }
    label.textColor = RGB_UI_COLOR(255, 211, 155);
    label.font = [UIFont systemFontOfSize:15 weight:0.5];
    
    return label;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 25.f;
}

#pragma mark - UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 0){//充值
        KLRechargeViewController *rechargeVC = [[KLRechargeViewController alloc]init];
        [self.navigationController pushViewController:rechargeVC animated:YES];
    }else if(buttonIndex == 1){//在线支付
        [KLHelp showHUDAddedTo:self.view animated:YES];
        //设置支付代理
        [BeeCloud setBeeCloudDelegate:self];
        //充值
        [self recharge];
    }
}

#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    UITextField *feeField = [alertView textFieldAtIndex:0];
    NSLog(@"feeField:%@",feeField.text);
    factPayFee = feeField.text;
    
    if(buttonIndex == 1){
        //判断当前余额是否充足
//        NSString *amount = [[NSUserDefaults standardUserDefaults] objectForKey:@"feeaccount"];
        NSString *amount = @"100";

        
        if(feeField.text.doubleValue < minTotalFee.doubleValue){
            [KLHelp showTextHUDforView:self.view text:@"输入金额不得少于最低支付金额"];
            return ;
        }
        if(amount.doubleValue < feeField.text.doubleValue){
            self.money = [NSString stringWithFormat:@"%.f",factPayFee.doubleValue * 100];
            UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"当前余额不足" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"充值",@"在线支付", nil];
            [sheet showInView:self.view];
            return ;
        }
        //申请钥匙
        [self applyKey];
    }
}

-(void)recharge{
    //本机当前时间(用于自定义单号)
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    //支付请求
    [BeeCloud initWithAppID:@"1e70e317-1286-490b-ad3b-3d56f8f2e0a0" andAppSecret:@"caf7da3a-1b60-499c-920c-5d0c2008693a"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.money,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"], nil];
    BCPayReq *payReq = [[BCPayReq alloc] init];
    payReq.channel = PayChannelAliApp; //支付渠道
    payReq.title = @"KISSLOCK申请钥匙在线支付";//订单标题
    payReq.totalFee = [NSString stringWithFormat:@"%@",self.money];//订单价格
    self.trade_no = [NSString stringWithFormat:@"0004%@%@",locationString,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]];//商户自定义订单号
    payReq.billNo = self.trade_no;
    NSLog(@"trade_no:%@",self.trade_no);
    payReq.scheme = @"prefsGuoYangKissLock";//URL Scheme,在Info.plist中配置; 支付宝必有参数
    payReq.billTimeOut = 300;//订单超时时间
    payReq.viewController = self; //银联支付和Sandbox环境必填
    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
    [BeeCloud sendBCReq:payReq];
}

#pragma mark - BCPay回调
- (void)onBeeCloudResp:(BCBaseResp *)resp {
    [KLHelp hideAllHUDsForView:self.view animated:YES];
    if(resp.type == BCObjsTypePayResp){
        // 支付请求响应
        BCPayResp *tempResp = (BCPayResp *)resp;
        if (tempResp.resultCode == 0) {
            NSLog(@"支付情况：%@",resp.resultMsg);
            [KLHttpAPI payoffSuccessWithKeytype:@"2" total_fee:self.money trade_no:self.trade_no completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"充值返回数据：%@",operation.responseString);
                NSDictionary *dic = operation.responseJSON;
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [[NSUserDefaults standardUserDefaults] setObject:[dic objectForKey:@"msg"] forKey:@"feeaccount"];
                    /*此处为申请钥匙的提交接口*/
                    [self applyKey];
                }else{
                    [KLHelp showTextHUDforView:self.view text:@"充值失败"];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp showTextHUDforView:self.view text:@"网络波动，充值失败"];
            }];
        } else {
            //支付取消或者支付失败
            NSLog(@"支付取消或失败结果信息:resultMsg：%@, errDetail：%@, type：%zd, resultCode：%zd",tempResp.resultMsg,tempResp.errDetail,tempResp.request.type,tempResp.resultCode);
            [KLHelp showTextHUDforView:self.view text:tempResp.resultMsg];
        }
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [messageView resignFirstResponder];
}

#pragma marl - 推出时间选择器视图
-(void)showTimeControlView:(UIButton *)sender{
    if(timeCoverView){
        [timeCoverView removeFromSuperview];
    }
    
    timeCoverView = [[UIView alloc]initWithFrame:CGRectMake(0, UI_View_Height, UI_View_Width, 315)];
    timeCoverView.backgroundColor = RGB_UI_COLOR(255, 211, 155);
    timeCoverView.layer.masksToBounds = YES;
    timeCoverView.layer.cornerRadius = 10;
    [self.view addSubview:timeCoverView];
    
    UIButton *confirmTimeBtn = [[UIButton alloc]init];
    [confirmTimeBtn setTitle:@"确定" forState:UIControlStateNormal];
    [confirmTimeBtn setTitleColor:RGB_UI_COLOR(109, 158, 235) forState:UIControlStateNormal];
    confirmTimeBtn.layer.masksToBounds = YES;
    confirmTimeBtn.layer.cornerRadius = 5;
    confirmTimeBtn.layer.borderColor = RGB_UI_COLOR(109, 158, 235).CGColor;
    confirmTimeBtn.layer.borderWidth = 0.8;
    [confirmTimeBtn addTarget:self action:@selector(confirmTime:) forControlEvents:UIControlEventTouchUpInside];
    [timeCoverView addSubview:confirmTimeBtn];
    [confirmTimeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(27);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(7);
    }];
    
    UUDatePicker *datePicker
    = [[UUDatePicker alloc]initWithframe:CGRectMake(0, 0, 0, 0)
                             PickerStyle:0
                             didSelected:^(NSString *year,
                                           NSString *month,
                                           NSString *day,
                                           NSString *hour,
                                           NSString *minute,
                                           NSString *weekDay) {
                                 NSString *timeStr = [NSString stringWithFormat:@"%@-%@-%@ %@:%@",year,month,day,hour,minute];
                                 if (sender == timeBtnStart) {
                                     self.startYear = year;
                                     self.startMonth = month;
                                     self.startDay = day;
                                     self.startHour = hour;
                                     self.startMin = minute;
                                     
                                     [timeBtnStart setTitle:timeStr forState:UIControlStateNormal];
                                     [timeBtnStart setImage:nil forState:UIControlStateNormal];
                                 }else if(sender == timeBtnEnd){
                                     self.endYear = year;
                                     self.endMonth = month;
                                     self.endDay = day;
                                     self.endHour = hour;
                                     self.endMin = minute;
                                     
                                     [timeBtnEnd setTitle:timeStr forState:UIControlStateNormal];
                                     [timeBtnEnd setImage:nil forState:UIControlStateNormal];
                                 }
                             }];
    if(sender == timeBtnStart){
        datePicker.minLimitDate = [NSDate date];
        if(self.endYear != nil){
            NSString *maxStr = [NSString stringWithFormat:@"%@%@%@%@%@",self.endYear,self.endMonth,self.endDay,self.endHour,self.endMin];
            NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
            [dateFormat setDateFormat:@"yyyyMMddHHmm"];
            datePicker.maxLimitDate = [dateFormat dateFromString:maxStr];
        }
    }else if(sender == timeBtnEnd){
        if(self.startYear == nil){
            datePicker.minLimitDate = [NSDate date];
        }else{
            NSString *minStr = [NSString stringWithFormat:@"%@%@%@%@%@",self.startYear,self.startMonth,self.startDay,self.startHour,self.startMin];
            NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
            [dateFormat setDateFormat:@"yyyyMMddHHmm"];
            datePicker.minLimitDate = [dateFormat dateFromString:minStr];
        }
    }
    datePicker.ScrollToDate = datePicker.minLimitDate;
    datePicker.backgroundColor = [UIColor clearColor];
    [timeCoverView addSubview:datePicker];
    [datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(300);
        make.height.mas_equalTo(200);
        make.top.mas_equalTo(40);
        make.centerX.equalTo(timeCoverView);
    }];
    
    //不滚动时的初始化时间
    NSDateFormatter *dft = [[NSDateFormatter alloc]init];
    if(sender == timeBtnStart){
        [dft setDateFormat:@"YYYY"];
        self.startYear = [dft stringFromDate:datePicker.minLimitDate];
        [dft setDateFormat:@"MM"];
        self.startMonth = [dft stringFromDate:datePicker.minLimitDate];
        [dft setDateFormat:@"dd"];
        self.startDay = [dft stringFromDate:datePicker.minLimitDate];
        [dft setDateFormat:@"HH"];
        self.startHour = [dft stringFromDate:datePicker.minLimitDate];
        [dft setDateFormat:@"mm"];
        self.startMin = [dft stringFromDate:datePicker.minLimitDate];
        NSString *timeStr = [NSString stringWithFormat:@"%@-%@-%@ %@:%@",self.startYear,self.startMonth,self.startDay,self.startHour,self.startMin];
        [timeBtnStart setTitle:timeStr forState:UIControlStateNormal];
        [timeBtnStart setImage:nil forState:UIControlStateNormal];
    }else if(sender == timeBtnEnd){
        [dft setDateFormat:@"YYYY"];
        self.endYear = [dft stringFromDate:datePicker.minLimitDate];
        [dft setDateFormat:@"MM"];
        self.endMonth = [dft stringFromDate:datePicker.minLimitDate];
        [dft setDateFormat:@"dd"];
        self.endDay = [dft stringFromDate:datePicker.minLimitDate];
        [dft setDateFormat:@"HH"];
        self.endHour = [dft stringFromDate:datePicker.minLimitDate];
        [dft setDateFormat:@"mm"];
        self.endMin = [dft stringFromDate:datePicker.minLimitDate];
        NSString *timeStr = [NSString stringWithFormat:@"%@-%@-%@ %@:%@",self.endYear,self.endMonth,self.endDay,self.endHour,self.endMin];
        [timeBtnEnd setTitle:timeStr forState:UIControlStateNormal];
        [timeBtnEnd setImage:nil forState:UIControlStateNormal];
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        timeCoverView.frame = CGRectMake(0, UI_View_Height-315, UI_View_Width, 315);
    }];
}-(void)confirmTime:(UIButton *)sender{
    [UIView animateWithDuration:0.3 animations:^{
        timeCoverView.frame = CGRectMake(0, UI_View_Height, UI_View_Width, 315);
    }];
}

#pragma mark - 申请钥匙
-(void)applyKey{
    //申请钥匙
    NSString *startTime = [NSString stringWithFormat:@"%@-%@-%@ %@:%@:00",self.startYear,self.startMonth,self.startDay,self.startHour,self.startMin];
    NSString *endTime = [NSString stringWithFormat:@"%@-%@-%@ %@:%@:00",self.endYear,self.endMonth,self.endDay,self.endHour,self.endMin];
    [KLHelp showHUDAddedTo:self.view animated:YES];
    NSLog(@"-------------%@",typeSelect);
    [KLHttpAPI requestApplyForKeysWithMoblie:self.phoneTF.text prict:factPayFee startDate:startTime endDate:endTime lockid:self.selectedLockListArr message:msg type:typeSelect completionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"operation:%@",operation.responseString);
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
    }];
}

#pragma mark - 获取申请钥匙的历史记录
-(void)applyList:(id)sender{
    KLHistoryApplyKeyListTableViewController *historyVC = [[KLHistoryApplyKeyListTableViewController alloc]init];
    [self presentViewController:historyVC animated:YES completion:nil];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
